﻿#pragma once
#include <QWidget>
#include <QDebug>
// #include <mqtt/async_client.h>
#include "ui_mqtt.h"
#include "SubTopicInfoEntity.h"
#include "PubTopicInfoEntity.h"
#include <qstandarditemmodel.h>
#include <QtMqtt/qmqttclient.h>

class MessageArrivedModel;

class MqttWidget : public QWidget
{
	Q_OBJECT
public:
	MqttWidget(QWidget *parent = nullptr);

	~MqttWidget();

	// void connected(const std::string &cause) override { emit mqtt_connected(QString::fromStdString(cause)); }
	// void connection_lost(const std::string &cause) override { emit mqtt_connection_lost(QString::fromStdString(cause)); }
	// void message_arrived(mqtt::const_message_ptr msg) override { emit mqtt_messageArrived(msg->get_topic().c_str(), msg->to_string().c_str(), msg->get_qos(), msg->is_retained()); }

private slots:
	void on_payload_plain_text_edit_changed();

	void on_send_msg_btn_clicked();
	void on_hex_checkbox_state_changed();
	void on_export_btn_clicked();
	void on_clear_btn_clicked();

	void on_delete_sub_topic_btn_clicked();
	void on_add_sub_topic_btn_clicked();
	void on_sub_topic_item_changed(QStandardItem *item);
	void on_enable_sub_topic_item_changed();
	void on_sub_topic_item_hex_state_changed();

	void on_sub_topic_table_view_context_menu_requested(const QPoint &pos);

	void on_add_pub_topic_btn_clicked();
	void on_save_pub_topic_btn_clicked();
	void on_cancel_pub_topic_btn_clicked();
	void on_delete_pub_topic_btn_clicked();
	void on_edit_pub_topic_btn_clicked();
	void on_select_pub_topic_btn_clicked();

	void on_connect_btn_clicked();
	void on_host_edit_text_changed(const QString &text);
	void on_name_edit_text_changed(const QString &text);
	void on_name_model_inserted(const QModelIndex &parent, int first, int last);
	void on_delete_name_btn_clicked();
	void on_current_name_changed(const QString &text);

	void on_mqtt_connected();
	void on_mqtt_disconnect();
	void on_mqtt_message_arrived(const QByteArray &message, const QMqttTopicName &topic);

private:
	void set_sub_topic_row_editable(int row, bool editable);
	void save_sub_topic_info();
	void add_sub_topic_info(const SubTopicInfoEntity &info);

	void add_or_update_pub_topic_info(PubTopicInfoEntity &info);
	void add_pub_topic_info(const PubTopicInfoEntity &info);

	SubTopicInfoEntity get_sub_topic_info(int row);

	PubTopicInfoEntity get_pub_topic_info(int row);

	// signals:
	//	void mqtt_connected(const QString &cause);
	//	void mqtt_connection_lost(const QString &cause);
	//	void mqtt_messageArrived(const QString &topic, const QString &payload, int qos, bool retained);

private:
	Ui::Form ui;
	// mqtt::async_client *client;
	QStandardItemModel *message_arrived_model;
	QStandardItemModel *sub_topic_info_model;
	QStandardItemModel *pub_topic_info_model;
	QStandardItemModel *name_model;

	// auto send timer
	QTimer *auto_send_timer;

	QMqttClient *m_client;
};
